<template>
  <div class="carbon-sink-data-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="140px">
      <template v-for="(item, index) in formList">
        <el-form-item
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-if="item.prop"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)"
          >
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import roomApi from '@/api/apis/sceneRoom'
import { parseSceneData } from '@/utils/scene-data'

export default {
  name: 'AddCarbonSinkData',
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      formData: {
        label: '',
        value: '',
        remark: ''
      },
      formList: [
        {
          name: '项目名称',
          prop: 'sceneProjectId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'SceneProjectSelected'
          },
          attrConfig: {
            placeholder: '请选择所属项目',
            style: { width: '100%' },
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '所属场景',
          prop: 'roomInfo',
          componentType: 'el-cascader',
          attrConfig: {
            style: { width: '100%' },
            placeholder: '请选择所属场景',
            props: {
              checkStrictly: true
            },
            options: []
          }
        },
        {
          name: '绿化名称',
          prop: 'type',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'CarbonSinkSelected'
          },
          attrConfig: {
            placeholder: '请选择绿化名称',
            style: { width: '100%' },
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        }, {
          name: '种植方式',
          prop: 'carbonSinkId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'CarbonSinkFactorSelected'
          },
          attrConfig: {
            placeholder: '请选择种植方式',
            style: { width: '100%' },
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' }
        },
        {
          name: '面积(㎡)',
          prop: 'area',
          attrConfig: {
            placeholder: '请输入面积(㎡)',
            type: 'number'
          },
          disabled: true
        },
        {
          name: '碳汇（kgCO2）',
          prop: 'carbonEmission',
          attrConfig: {
            placeholder: '请输入碳汇（kgCO2）',
            disabled: true,
            type: 'number'
          },
          disabled: true
        },
        {
          name: '数据时间',
          prop: 'solidifyDate',
          attrConfig: {
            placeholder: '年-月-日',
            valueFormat: 'yyyy-MM-dd',
            format: 'yyyy-MM-dd'
          },
          componentType: 'el-date-picker',
          style: { width: '100%' }
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        sceneProjectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
        roomInfo: [{ required: true, message: '请选择所属场景', trigger: 'change' }],
        solidifyDate: [{ required: true, message: '请选择数据时间', trigger: 'change' }],
        carbonSinkId: [{ required: true, message: '请选择种植方式', trigger: 'change' }],
        type: [{ required: true, message: '请选择植被类型', trigger: 'change' }],
        area: [{ required: true, message: '请输入面积', trigger: 'blur' }]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
        })
        this.$set(this.formData, 'id', data.id)
        if (data.sceneProjectId != null) {
          this.getRoomList(data.sceneProjectId)
          if (data.sceneEdificeId && data.sceneFloorId && data.sceneRoomId) {
            this.formData.roomInfo = [data.sceneEdificeId, data.sceneFloorId, data.sceneRoomId]
          }
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    async getRoomList(sceneProjectId) {
      const res = await roomApi.queryRoomList({
        sceneProjectId,
        sortColumn: 'floorName',
        sortOrder: 'asc'
      })
      const roomList = parseSceneData(res.data)
      const item = this.formList[1]
      item.attrConfig.options = roomList
      this.$set(this.formList, 1, { ...item })
    },

    calculateCarbonEmission() {
      if (this.formData.carbonSinkId && this.formData.area) {
        const area = Number(this.formData.area)
        const carbonSink = this.formList[3].optionList.find(item => item.value === this.formData.carbonSinkId)
        this.formData.carbonEmission = (area * carbonSink.baseObj.factor / 365).toFixed(8)
      } else {
        this.formData.carbonEmission = null
      }
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
      if (config.prop === 'sceneProjectId') {
        this.getRoomList(this.formData.sceneProjectId)
      } else if (config.prop === 'carbonSinkId' || config.prop === 'area') {
        this.calculateCarbonEmission()
      } else if (config.prop === 'roomInfo') {
        const roomInfo = this.formData.roomInfo
        if (roomInfo == null || roomInfo.length === 0) {
          this.formData.sceneEdificeId = null
          this.formData.sceneFloorId = null
          this.formData.sceneRoomId = null
        } else {
          this.formData.sceneEdificeId = roomInfo[0]
          this.formData.sceneFloorId = roomInfo[1]
          this.formData.sceneRoomId = roomInfo[2]
        }
      }
      console.log(this.formData)

    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$api.carbonSinkData[
            this.isAdd ? 'add' : 'update'
            ](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'carbon-sink-data-add')
          }
        }
      })
    }
  }
}
</script>

<!--<style lang="scss" scoped>-->
<!--  .carbon-sink-data-box {-->
<!--    color: #333;-->
<!--    padding: 0 20px;-->

<!--    ::v-deep .el-form {-->
<!--      display: flex;-->
<!--      flex-wrap: wrap;-->
<!--      justify-content: space-between;-->

<!--      .el-form-item {-->
<!--        width: calc(50% - 10px);-->

<!--        &.width100p {-->
<!--          width: 100%;-->
<!--        }-->

<!--        .el-form-item__label {-->
<!--          color: #666;-->
<!--          font-size: 14px;-->
<!--        }-->

<!--        &.form-sub-title {-->
<!--          width: 100%;-->

<!--          .el-form-item__label {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            justify-content: flex-start;-->
<!--            font-weight: bold;-->
<!--            color: #333;-->
<!--            font-size: 16px;-->
<!--            line-height: 1;-->

<!--            &::before {-->
<!--              content: '';-->
<!--              display: inline-block;-->
<!--              width: 4px;-->
<!--              height: 15px;-->
<!--              background-color: #00858d;-->
<!--              margin-right: 5px;-->
<!--            }-->
<!--          }-->
<!--        }-->
<!--      }-->

<!--      .el-select,-->
<!--      .el-cascader {-->
<!--        width: 100%;-->
<!--      }-->
<!--    }-->
<!--  }-->
<!--</style>-->
